package com.caigou.modules.rank.ui.level

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.viewmodel.FollowViewModel
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.rank.R
import com.caigou.modules.rank.adapter.LevelRankItemAdapter
import com.caigou.modules.rank.bean.LevelRankBean
import com.caigou.modules.rank.bean.LevelRankItemBean
import com.caigou.modules.rank.databinding.FragmentTotalLevelRankBinding
import com.caigou.modules.rank.viewmodel.RankViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/11/05
 */
@AndroidEntryPoint
class TotalLevelRankFragment : BaseFragment() {

    private var _binding: FragmentTotalLevelRankBinding? = null
    private val binding get() = _binding!!

    private val rankViewModel: RankViewModel by viewModels()
    private val followViewModel: FollowViewModel by viewModels()

    private var headerList = mutableListOf<LevelRankItemBean>()

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(requireActivity())
    }

    private val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(requireActivity())
    }

    private val mAdapter: LevelRankItemAdapter by lazy {
        LevelRankItemAdapter(mutableListOf())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentTotalLevelRankBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.totalLevelRankSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                rankViewModel.getLevelRank("", AppBackgroundInfo.instance.userBean!!.userId)
            }
        }

        binding.totalLevelRankRecyclerView.run {
            layoutManager = linearLayoutManager
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }

        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = mAdapter.getItem(position)
            when (view.id) {
                R.id.item_level_rank_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.userId)
                        .navigation()
                }
                R.id.item_level_rank_btn_follow -> {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, item.userId)
                }
            }
        }

        binding.totalLevelRankIvAvatar.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                .withString(AppConstants.USER_ID, AppBackgroundInfo.instance.userBean!!.userId)
                .navigation()
        }
    }

    override fun lazyLoad() {
        rankViewModel.getLevelRank("", AppBackgroundInfo.instance.userBean!!.userId)
    }

    override fun onBack() {
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(rankViewModel.levelRankViewModel, ::handleGetLevelRank)
        observe(followViewModel.followLiveData, ::handleSetFollow)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleLadder() {
        when (headerList.size) {
            1 -> {
                binding.totalLevelRankLayoutLadder.ladderTvNickname1.text = headerList[0].nickName
                binding.totalLevelRankLayoutLadder.ladderTvNum1.text = headerList[0].growthValue.toString()
                if (TextUtils.isEmpty(headerList[0].headImg)) {
                    binding.totalLevelRankLayoutLadder.ladderIvAvatar1.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[0].headImg, binding.totalLevelRankLayoutLadder.ladderIvAvatar1)
                }
                if (headerList[0].concern) {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.text = "已关注"
                } else {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.text = "+关注"
                }

                binding.totalLevelRankLayoutLadder.ladderIvAvatar1.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[0].userId)
                        .navigation()
                }

                binding.totalLevelRankLayoutLadder.ladderBtnFollow1.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[0].userId)
                }
            }
            2 -> {
                binding.totalLevelRankLayoutLadder.ladderTvNickname1.text = headerList[0].nickName
                binding.totalLevelRankLayoutLadder.ladderTvNum1.text = headerList[0].growthValue.toString()
                if (TextUtils.isEmpty(headerList[0].headImg)) {
                    binding.totalLevelRankLayoutLadder.ladderIvAvatar1.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[0].headImg, binding.totalLevelRankLayoutLadder.ladderIvAvatar1)
                }
                if (headerList[0].concern) {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.text = "已关注"
                } else {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.text = "+关注"
                }

                binding.totalLevelRankLayoutLadder.ladderTvNickname2.text = headerList[1].nickName
                binding.totalLevelRankLayoutLadder.ladderTvNum2.text = headerList[1].growthValue.toString()
                if (TextUtils.isEmpty(headerList[1].headImg)) {
                    binding.totalLevelRankLayoutLadder.ladderIvAvatar2.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[1].headImg, binding.totalLevelRankLayoutLadder.ladderIvAvatar2)
                }
                if (headerList[1].concern) {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow2.text = "已关注"
                } else {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow2.text = "+关注"
                }

                binding.totalLevelRankLayoutLadder.ladderIvAvatar1.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[0].userId)
                        .navigation()
                }

                binding.totalLevelRankLayoutLadder.ladderIvAvatar2.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[1].userId)
                        .navigation()
                }

                binding.totalLevelRankLayoutLadder.ladderBtnFollow1.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[0].userId)
                }

                binding.totalLevelRankLayoutLadder.ladderBtnFollow2.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[1].userId)
                }
            }
            3 -> {
                binding.totalLevelRankLayoutLadder.ladderTvNickname1.text = headerList[0].nickName
                binding.totalLevelRankLayoutLadder.ladderTvNum1.text = headerList[0].growthValue.toString()
                if (TextUtils.isEmpty(headerList[0].headImg)) {
                    binding.totalLevelRankLayoutLadder.ladderIvAvatar1.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[0].headImg, binding.totalLevelRankLayoutLadder.ladderIvAvatar1)
                }
                if (headerList[0].concern) {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.text = "已关注"
                } else {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow1.text = "+关注"
                }

                binding.totalLevelRankLayoutLadder.ladderTvNickname2.text = headerList[1].nickName
                binding.totalLevelRankLayoutLadder.ladderTvNum2.text = headerList[1].growthValue.toString()
                if (TextUtils.isEmpty(headerList[1].headImg)) {
                    binding.totalLevelRankLayoutLadder.ladderIvAvatar2.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[1].headImg, binding.totalLevelRankLayoutLadder.ladderIvAvatar2)
                }
                if (headerList[1].concern) {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow2.text = "已关注"
                } else {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow2.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow2.text = "+关注"
                }

                binding.totalLevelRankLayoutLadder.ladderTvNickname3.text = headerList[2].nickName
                binding.totalLevelRankLayoutLadder.ladderTvNum3.text = headerList[2].growthValue.toString()
                if (TextUtils.isEmpty(headerList[2].headImg)) {
                    binding.totalLevelRankLayoutLadder.ladderIvAvatar3.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), headerList[2].headImg, binding.totalLevelRankLayoutLadder.ladderIvAvatar3)
                }
                if (headerList[2].concern) {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow3.setBackgroundResource(R.drawable.comm_btn_gray2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow3.text = "已关注"
                } else {
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow3.setBackgroundResource(R.drawable.comm_btn_red2)
                    binding.totalLevelRankLayoutLadder.ladderBtnFollow3.text = "+关注"
                }


                binding.totalLevelRankLayoutLadder.ladderIvAvatar1.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[0].userId)
                        .navigation()
                }

                binding.totalLevelRankLayoutLadder.ladderIvAvatar2.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[1].userId)
                        .navigation()
                }

                binding.totalLevelRankLayoutLadder.ladderIvAvatar3.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, headerList[2].userId)
                        .navigation()
                }

                binding.totalLevelRankLayoutLadder.ladderBtnFollow1.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[0].userId)
                }

                binding.totalLevelRankLayoutLadder.ladderBtnFollow2.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[1].userId)
                }

                binding.totalLevelRankLayoutLadder.ladderBtnFollow3.setOnClickListener {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, headerList[2].userId)
                }
            }
        }
    }

    private fun handleGetLevelRank(result: Resource<LevelRankBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.totalLevelRankSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取等级排行榜信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.totalLevelRankSwipeRefreshLayout.isRefreshing = false

                if (result.data == null) {
                    return
                }

                if (TextUtils.isEmpty(result.data!!.headImg)) {
                    binding.totalLevelRankIvAvatar.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(requireActivity(), result.data!!.headImg, binding.totalLevelRankIvAvatar)
                }
                binding.totalLevelRankTvNum.text = result.data!!.value.toString()
                binding.totalLevelRankTvIndex.text = result.data!!.rank

                headerList.clear()
                val tempList = mutableListOf<LevelRankItemBean>()
                for (index in 0 until result.data!!.list.size) {
                    if (index <= 2) {
                        headerList.add(result.data!!.list[index])
                    } else {
                        tempList.add(result.data!!.list[index])
                    }
                }
                mAdapter.setList(tempList)
                handleLadder()
            }
        }
    }

    private fun handleSetFollow(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("关注异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                result.data?.apply {
                    showToast(result.data!!)
                }
                rankViewModel.getLevelRank("", AppBackgroundInfo.instance.userBean!!.userId)
                LiveDataBus.get().with(BusKey.REFRESH_USER_INFO).value = Any()
            }
        }
    }
}